﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Scheduling.Models;
using Scheduling.Models.Interfaces;
using Scheduling.Models.Helpers;

namespace Scheduling.Controllers
{
    public class RoomController : BaseController
    {
        [HttpGet]
        public ActionResult List()
        {
            return View(new List<Room>());
        }

        [HttpGet]

        public ActionResult Show(String id)
        {
            var roomLoader = IoC.Resolve<IRoomLoader>();
            if (!roomLoader.RoomExists(id))
                FileNotFound();

            var room = roomLoader.GetRoom(id);
            return View(room);
        }

        [HttpGet]
        [Restrict(Roles = "Administrators")]
        public ActionResult Add()
        {
            var propertyLoader = IoC.Resolve<IRoomPropertyLoader>();
            List<RoomProperty> propertyList = propertyLoader.GetAllRoomProperties();
            string fieldData = "";
            ViewData["roomProperties"] = propertyList;
            foreach (RoomProperty rp in propertyList)
            {
                fieldData += (rp.Name + ",");
            }
            ViewData["fieldData"] = fieldData;
            return View();
        }

        [HttpPost]
        public ActionResult List(string inSearchRoomPattern)
        {
            var roomLoader = IoC.Resolve<IRoomLoader>();
            ViewData["inSearchRoomPattern"] = inSearchRoomPattern;
            return View(roomLoader.SearchRoomsByPatten(inSearchRoomPattern).Take(50));
        }

        [HttpPost]
        [Restrict(Roles = "Administrators")]
        public ActionResult Add(string inRoomID, string inRoomName, int? inRoomCapacity, string inRoomDescription, string[] inField, string[] inFieldVals)
        {
            string message = "";
            var roomLoader = IoC.Resolve<IRoomLoader>();
            var propertyLoader = IoC.Resolve<IRoomPropertyLoader>();
            if (string.IsNullOrEmpty(inRoomID.Trim()))
                message += "Room ID may not be empty.<br />";
            else if(roomLoader.RoomExists(inRoomID))
                message += "Room already exists in the database <br />";
            if (inRoomDescription.Length > 50)
                message += "Room description is too long (" + inRoomDescription.Length + " characters). Please reduce to 50.<br />";
            List<RoomProperty> RoomPropList = new List<RoomProperty>();
            MakeRoomPropList(inField, inFieldVals, RoomPropList,ref message);
            if (message != "")
            {
                ViewData["message"] = MvcHtmlString.Create(message);
                ViewData["roomID"] = inRoomID;
                ViewData["roomName"] = inRoomName;
                ViewData["roomCapacity"] = inRoomCapacity;
                ViewData["roomDescription"] = inRoomDescription;
                ViewData["props"] = inField;
                ViewData["propVals"] = inFieldVals;
                string fieldData = "";
                foreach (RoomProperty rp in propertyLoader.GetAllRoomProperties())
                {
                    fieldData += (rp.Name + ",");
                }
                ViewData["fieldData"] = fieldData;
                return View();
            }

            roomLoader.InsertRoom(new Room() { ID = inRoomID, Name = inRoomName, Capacity = inRoomCapacity, Description = inRoomDescription, Properties = RoomPropList });
            return RedirectToAction("List");
        }

        private void MakeRoomPropList(string[] props, string[] propVals, List<RoomProperty> propList, ref string errMsg)
        {
            int[] vals = new int[propVals.Count()];
            for (int i = 0; i < propVals.Count(); i++)
            {
                if (string.IsNullOrEmpty(propVals[i].Trim()) && !(string.IsNullOrEmpty(props[i].Trim())))
                {
                    errMsg += "One or more of the properties are missing values.<br />";
                    return;
                }
            }

            for (int i = 0; i < vals.Count(); i++)
            {
                if ((!(int.TryParse(propVals[i], out vals[i])) || vals[i] < 0) && !string.IsNullOrEmpty(props[i].Trim()))
                {
                    errMsg += "Invalid property value of property.<br />";
                    return;
                }
            }
            for (int i = 0; i < props.Count(); i++)
            {
                if (string.IsNullOrEmpty(props[i].Trim()))
                    continue;
                propList.Add(new RoomProperty() { Name = props[i], Value = vals[i] });
            }
        }

        [HttpGet]
        [Restrict(Roles = "Administrators")]
        public ActionResult Edit(string id)
        {
            var roomLoader = IoC.Resolve<IRoomLoader>();
            var propertyLoader = IoC.Resolve<IRoomPropertyLoader>();
            Room room = roomLoader.GetRoom(id);
            ViewData["roomID"] = id;
            ViewData["roomName"] = room.Name;
            ViewData["roomCapacity"] = room.Capacity;
            ViewData["roomDescription"] = room.Description;
            String[] props = new String[room.Properties.Count];
            String[] propVals = new String[room.Properties.Count];
            for (int i = 0; i < room.Properties.Count; i++)
            {
                props[i] = room.Properties.ElementAt(i).Name;
                propVals[i] = room.Properties.ElementAt(i).Value.ToString();
            }
            ViewData["props"] = props;
            ViewData["propVals"] = propVals;
            string properties = "";
            List<RoomProperty> something = propertyLoader.GetAllRoomProperties();
            foreach (RoomProperty p in something)
            {
                properties += (p.Name + ",");
            }
            ViewData["fieldData"] = properties;

            return View();
        }

        [HttpPost]
        [Restrict(Roles = "Administrators")]
        public ActionResult Edit(string inRoomID, string inRoomName, int? inRoomCapacity, string inRoomDescription, string[] inField, string[] inFieldVals)
        {
            string message = "";
            var roomLoader = IoC.Resolve<IRoomLoader>();
            var propertyLoader = IoC.Resolve<IRoomPropertyLoader>();
            if (inRoomDescription.Length > 50)
                message += "Room description is too long (" + inRoomDescription.Length + " characters). Please reduce to 50.<br />";
            List<RoomProperty> RoomPropList = new List<RoomProperty>();
            MakeRoomPropList(inField, inFieldVals, RoomPropList, ref message);
            if (message != "")
            {
                ViewData["message"] = MvcHtmlString.Create(message);
                ViewData["roomID"] = inRoomID;
                ViewData["roomName"] = inRoomName;
                ViewData["roomCapacity"] = inRoomCapacity;
                ViewData["roomDescription"] = inRoomDescription;
                ViewData["props"] = inField;
                ViewData["propVals"] = inFieldVals;
                string fieldData = "";
                foreach (RoomProperty rp in propertyLoader.GetAllRoomProperties())
                {
                    fieldData += (rp.Name + ",");
                }
                ViewData["fieldData"] = fieldData;
                return View();
            }

            roomLoader.EditRoom(new Room() { ID = inRoomID, Name = inRoomName, Capacity = inRoomCapacity, Description = inRoomDescription, Properties = RoomPropList });
            return RedirectToAction("Show", new { id=inRoomID });
        }

        [Restrict(Roles = "Administrators")]
        public ActionResult Delete(string id)
        {
            var roomLoader = IoC.Resolve<IRoomLoader>();
            if (!roomLoader.RoomExists(id))
                return Content(FileNotFound());
            
            roomLoader.DeleteRoom(id);
            return RedirectToAction("list");
            
        }
    }
}
